

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="Blue~u~u~u">
  <meta name="author" content="Blue~u~u~u">
  <meta name="keywords" content="">
  <meta name="description" content="中介者模式传统案例 智能家居项目，智能家庭包括各种设备，闹钟，咖啡机，电视机，窗帘等 主人要看电视时，各个设备可以完成看电视的准备工作，比如流程为：闹铃响起，咖啡机开始做咖啡，窗帘自动落下，电视开始播放。 基本介绍 中介者模式(Mediator Pattern)，    用一个中介者对象来封装一系列的交互对象，中介者使各个对象不需要显式的相互作用，从而使其耦合松散，而且可以独立的改变他们之间的交互">
<meta property="og:type" content="article">
<meta property="og:title" content="java-中介者模式">
<meta property="og:url" content="http://www.slx.blue/2021/12/09/java-mediator/index.html">
<meta property="og:site_name" content="Blue~u~u~u~u">
<meta property="og:description" content="中介者模式传统案例 智能家居项目，智能家庭包括各种设备，闹钟，咖啡机，电视机，窗帘等 主人要看电视时，各个设备可以完成看电视的准备工作，比如流程为：闹铃响起，咖啡机开始做咖啡，窗帘自动落下，电视开始播放。 基本介绍 中介者模式(Mediator Pattern)，    用一个中介者对象来封装一系列的交互对象，中介者使各个对象不需要显式的相互作用，从而使其耦合松散，而且可以独立的改变他们之间的交互">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://lllong.oss-cn-shenzhen.aliyuncs.com/JavaDesignMode/mediator/mediator01.png">
<meta property="og:image" content="https://lllong.oss-cn-shenzhen.aliyuncs.com/JavaDesignMode/mediator/mediator02.png">
<meta property="article:published_time" content="2021-12-09T06:02:37.000Z">
<meta property="article:modified_time" content="2022-01-25T12:50:01.052Z">
<meta property="article:author" content="Blue~u~u~u">
<meta property="article:tag" content="设计模式">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://lllong.oss-cn-shenzhen.aliyuncs.com/JavaDesignMode/mediator/mediator01.png">
  
  <title>java-中介者模式 - Blue~u~u~u~u</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"www.slx.blue","root":"/","version":"1.8.12","typing":{"enable":true,"typeSpeed":180,"cursorChar":"_","loop":true},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname"}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>

<script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome/css/font-awesome.min.css"/>
<script src="/live2d-widget/autoload.js"></script>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Blue~u~u</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/links/">
                <i class="iconfont icon-link-fill"></i>
                友链
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/images/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="java-中介者模式">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-12-09 14:02" pubdate>
        2021年12月9日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      5.5k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      17 分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">java-中介者模式</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：4 个月前
                
              </p>
            
            <div class="markdown-body">
              <h3 id="中介者模式"><a href="#中介者模式" class="headerlink" title="中介者模式"></a>中介者模式</h3><p>传统案例</p>
<p>智能家居项目，智能家庭包括各种设备，闹钟，咖啡机，电视机，窗帘等</p>
<p>主人要看电视时，各个设备可以完成看电视的准备工作，比如流程为：闹铃响起，咖啡机开始做咖啡，窗帘自动落下，电视开始播放。</p>
<h4 id="基本介绍"><a href="#基本介绍" class="headerlink" title="基本介绍"></a>基本介绍</h4><ol>
<li>中介者模式(Mediator Pattern)，    用一个中介者对象来封装一系列的交互对象，中介者使各个对象不需要显式的相互作用，从而使其耦合松散，而且可以独立的改变他们之间的交互</li>
<li>中介者模式属于行为型模式，使代码易于维护</li>
<li>比如MVC模式，C(Controller控制器)是M(Model模型）和（View视图）的中介者，在前后端交互时气到了中间人的作用。</li>
</ol>
<p>原理类图</p>
<p><img src="https://lllong.oss-cn-shenzhen.aliyuncs.com/JavaDesignMode/mediator/mediator01.png" srcset="/img/loading.gif" lazyload alt="mediator"></p>
<p>类图说明</p>
<ol>
<li>Mediator就是抽象中介者，定义了同事对象到中介者对象的接口</li>
<li>Colleague是抽象同事类</li>
<li><code>ConcreteMediator</code> 具体的中介者对象，它需要知道所有的具体的同事类，即以一个集合来管理(<code>HashMap</code>)，并接受某个同事对象消息，完成相应的任务</li>
<li><code>ConcreteColleague</code> 具体的同事类，会有很多，每个同事只知道自己的行为，而不了解其他的行为(方法)，但是他们都依赖中介者对象。</li>
</ol>
<h4 id="代码实现"><a href="#代码实现" class="headerlink" title="代码实现"></a>代码实现</h4><p>实现类图：</p>
<p><img src="https://lllong.oss-cn-shenzhen.aliyuncs.com/JavaDesignMode/mediator/mediator02.png" srcset="/img/loading.gif" lazyload alt="mediator02"></p>
<p>代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//中介者抽象类</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Mediator</span> </span>&#123;<br>	<span class="hljs-comment">//将给中介者对象，加入到集合中</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Register</span><span class="hljs-params">(String colleagueName, Colleague colleague)</span></span>;<br><br>	<span class="hljs-comment">//接收消息, 具体的同事对象发出</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">GetMessage</span><span class="hljs-params">(<span class="hljs-keyword">int</span> stateChange, String colleagueName)</span></span>;<br><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">SendMessage</span><span class="hljs-params">()</span></span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//同事抽象类</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Colleague</span> </span>&#123;<br>	<span class="hljs-keyword">private</span> Mediator mediator;<br>	<span class="hljs-keyword">public</span> String name;<br><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Colleague</span><span class="hljs-params">(Mediator mediator, String name)</span> </span>&#123;<br>		<span class="hljs-keyword">this</span>.mediator = mediator;<br>		<span class="hljs-keyword">this</span>.name = name;<br>	&#125;<br><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> Mediator <span class="hljs-title">GetMediator</span><span class="hljs-params">()</span> </span>&#123;<br>		<span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.mediator;<br>	&#125;<br><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">SendMessage</span><span class="hljs-params">(<span class="hljs-keyword">int</span> stateChange)</span></span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//具体的中介者类</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ConcreteMediator</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Mediator</span> </span>&#123;<br>	<span class="hljs-comment">//集合，放入所有的同事对象</span><br>	<span class="hljs-keyword">private</span> HashMap&lt;String, Colleague&gt; colleagueMap;<br>	<span class="hljs-keyword">private</span> HashMap&lt;String, String&gt; interMap;<br><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ConcreteMediator</span><span class="hljs-params">()</span> </span>&#123;<br>		colleagueMap = <span class="hljs-keyword">new</span> HashMap&lt;String, Colleague&gt;();<br>		interMap = <span class="hljs-keyword">new</span> HashMap&lt;String, String&gt;();<br>	&#125;<br><br>	<span class="hljs-meta">@Override</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Register</span><span class="hljs-params">(String colleagueName, Colleague colleague)</span> </span>&#123;<br>		colleagueMap.put(colleagueName, colleague);<br><br>		<span class="hljs-keyword">if</span> (colleague <span class="hljs-keyword">instanceof</span> Alarm) &#123;<br>			interMap.put(<span class="hljs-string">&quot;Alarm&quot;</span>, colleagueName);<br>		&#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (colleague <span class="hljs-keyword">instanceof</span> CoffeeMachine) &#123;<br>			interMap.put(<span class="hljs-string">&quot;CoffeeMachine&quot;</span>, colleagueName);<br>		&#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (colleague <span class="hljs-keyword">instanceof</span> TV) &#123;<br>			interMap.put(<span class="hljs-string">&quot;TV&quot;</span>, colleagueName);<br>		&#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (colleague <span class="hljs-keyword">instanceof</span> Curtains) &#123;<br>			interMap.put(<span class="hljs-string">&quot;Curtains&quot;</span>, colleagueName);<br>		&#125;<br><br>	&#125;<br><br>	<span class="hljs-comment">//具体中介者的核心方法</span><br>	<span class="hljs-comment">//1. 根据得到消息，完成对应任务</span><br>	<span class="hljs-comment">//2. 中介者在这个方法，协调各个具体的同事对象，完成任务</span><br>	<span class="hljs-meta">@Override</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">GetMessage</span><span class="hljs-params">(<span class="hljs-keyword">int</span> stateChange, String colleagueName)</span> </span>&#123;<br><br>		<span class="hljs-comment">//处理闹钟发出的消息</span><br>		<span class="hljs-keyword">if</span> (colleagueMap.get(colleagueName) <span class="hljs-keyword">instanceof</span> Alarm) &#123;<br>			<span class="hljs-keyword">if</span> (stateChange == <span class="hljs-number">0</span>) &#123;<br>				((CoffeeMachine) (colleagueMap.get(interMap<br>						.get(<span class="hljs-string">&quot;CoffeeMachine&quot;</span>)))).StartCoffee();<br>				((TV) (colleagueMap.get(interMap.get(<span class="hljs-string">&quot;TV&quot;</span>)))).StartTv();<br>			&#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (stateChange == <span class="hljs-number">1</span>) &#123;<br>				((TV) (colleagueMap.get(interMap.get(<span class="hljs-string">&quot;TV&quot;</span>)))).StopTv();<br>			&#125;<br><br>		&#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (colleagueMap.get(colleagueName) <span class="hljs-keyword">instanceof</span> CoffeeMachine) &#123;<br>			((Curtains) (colleagueMap.get(interMap.get(<span class="hljs-string">&quot;Curtains&quot;</span>))))<br>					.UpCurtains();<br><br>		&#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (colleagueMap.get(colleagueName) <span class="hljs-keyword">instanceof</span> TV) &#123;<span class="hljs-comment">//如果TV发现消息</span><br><br>		&#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (colleagueMap.get(colleagueName) <span class="hljs-keyword">instanceof</span> Curtains) &#123;<br>			<span class="hljs-comment">//如果是以窗帘发出的消息，这里处理...</span><br>		&#125;<br><br>	&#125;<br><br>	<span class="hljs-meta">@Override</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">SendMessage</span><span class="hljs-params">()</span> </span>&#123;<br><br>	&#125;<br><br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//同事类</span><br><br><span class="hljs-comment">//具体的同事类</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Alarm</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Colleague</span> </span>&#123;<br><br>	<span class="hljs-comment">//构造器</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Alarm</span><span class="hljs-params">(Mediator mediator, String name)</span> </span>&#123;<br>		<span class="hljs-keyword">super</span>(mediator, name);<br>		<span class="hljs-comment">//在创建Alarm 同事对象时，将自己放入到ConcreteMediator 对象中[集合]</span><br>		mediator.Register(name, <span class="hljs-keyword">this</span>);<br>	&#125;<br><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">SendAlarm</span><span class="hljs-params">(<span class="hljs-keyword">int</span> stateChange)</span> </span>&#123;<br>		SendMessage(stateChange);<br>	&#125;<br><br>	<span class="hljs-meta">@Override</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">SendMessage</span><span class="hljs-params">(<span class="hljs-keyword">int</span> stateChange)</span> </span>&#123;<br>		<span class="hljs-comment">//调用的中介者对象的getMessage</span><br>		<span class="hljs-keyword">this</span>.GetMediator().GetMessage(stateChange, <span class="hljs-keyword">this</span>.name);<br>	&#125;<br><br>&#125;<br><br><span class="hljs-comment">//咖啡机</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CoffeeMachine</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Colleague</span> </span>&#123;<br><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">CoffeeMachine</span><span class="hljs-params">(Mediator mediator, String name)</span> </span>&#123;<br>		<span class="hljs-keyword">super</span>(mediator, name);<br>		mediator.Register(name, <span class="hljs-keyword">this</span>);<br>	&#125;<br><br>	<span class="hljs-meta">@Override</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">SendMessage</span><span class="hljs-params">(<span class="hljs-keyword">int</span> stateChange)</span> </span>&#123;<br>		<span class="hljs-keyword">this</span>.GetMediator().GetMessage(stateChange, <span class="hljs-keyword">this</span>.name);<br>	&#125;<br><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">StartCoffee</span><span class="hljs-params">()</span> </span>&#123;<br>		System.out.println(<span class="hljs-string">&quot;It&#x27;s time to startcoffee!&quot;</span>);<br>	&#125;<br><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">FinishCoffee</span><span class="hljs-params">()</span> </span>&#123;<br><br>		System.out.println(<span class="hljs-string">&quot;After 5 minutes!&quot;</span>);<br>		System.out.println(<span class="hljs-string">&quot;Coffee is ok!&quot;</span>);<br>		SendMessage(<span class="hljs-number">0</span>);<br>	&#125;<br>&#125;<br><br><span class="hljs-comment">//窗帘</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Curtains</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Colleague</span> </span>&#123;<br><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Curtains</span><span class="hljs-params">(Mediator mediator, String name)</span> </span>&#123;<br>		<span class="hljs-keyword">super</span>(mediator, name);<br>		mediator.Register(name, <span class="hljs-keyword">this</span>);<br>	&#125;<br><br>	<span class="hljs-meta">@Override</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">SendMessage</span><span class="hljs-params">(<span class="hljs-keyword">int</span> stateChange)</span> </span>&#123;<br>		<span class="hljs-keyword">this</span>.GetMediator().GetMessage(stateChange, <span class="hljs-keyword">this</span>.name);<br>	&#125;<br><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">UpCurtains</span><span class="hljs-params">()</span> </span>&#123;<br>		System.out.println(<span class="hljs-string">&quot;I am holding Up Curtains!&quot;</span>);<br>	&#125;<br><br>&#125;<br><br><span class="hljs-comment">//TV</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TV</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Colleague</span> </span>&#123;<br><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">TV</span><span class="hljs-params">(Mediator mediator, String name)</span> </span>&#123;<br>		<span class="hljs-keyword">super</span>(mediator, name);<br>		mediator.Register(name, <span class="hljs-keyword">this</span>);<br>	&#125;<br><br>	<span class="hljs-meta">@Override</span><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">SendMessage</span><span class="hljs-params">(<span class="hljs-keyword">int</span> stateChange)</span> </span>&#123;<br>		<span class="hljs-keyword">this</span>.GetMediator().GetMessage(stateChange, <span class="hljs-keyword">this</span>.name);<br>	&#125;<br><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">StartTv</span><span class="hljs-params">()</span> </span>&#123;<br>		System.out.println(<span class="hljs-string">&quot;It&#x27;s time to StartTv!&quot;</span>);<br>	&#125;<br><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">StopTv</span><span class="hljs-params">()</span> </span>&#123;<br>		System.out.println(<span class="hljs-string">&quot;StopTv!&quot;</span>);<br>	&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//Client</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClientTest</span> </span>&#123;<br><br>	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>		<span class="hljs-comment">//创建一个中介者对象</span><br>		Mediator mediator = <span class="hljs-keyword">new</span> ConcreteMediator();<br>		<br>		<span class="hljs-comment">//创建Alarm 并且加入到  ConcreteMediator 对象的HashMap</span><br>		Alarm alarm = <span class="hljs-keyword">new</span> Alarm(mediator, <span class="hljs-string">&quot;alarm&quot;</span>);<br>		<br>		<span class="hljs-comment">//创建了CoffeeMachine 对象，并  且加入到  ConcreteMediator 对象的HashMap</span><br>		CoffeeMachine coffeeMachine = <span class="hljs-keyword">new</span> CoffeeMachine(mediator, <span class="hljs-string">&quot;coffeeMachine&quot;</span>);<br>		<br>		<span class="hljs-comment">//创建 Curtains , 并  且加入到  ConcreteMediator 对象的HashMap</span><br>		Curtains curtains = <span class="hljs-keyword">new</span> Curtains(mediator, <span class="hljs-string">&quot;curtains&quot;</span>);<br>		TV tV = <span class="hljs-keyword">new</span> TV(mediator, <span class="hljs-string">&quot;TV&quot;</span>);<br>		<br>		<span class="hljs-comment">//让闹钟发出消息</span><br>		alarm.SendAlarm(<span class="hljs-number">0</span>);<br>		coffeeMachine.FinishCoffee();<br>		alarm.SendAlarm(<span class="hljs-number">1</span>);<br>	&#125;<br><br>&#125;<br></code></pre></td></tr></table></figure>



<h4 id="源码分析"><a href="#源码分析" class="headerlink" title="源码分析"></a>源码分析</h4><blockquote>
<p><code>MVC</code>模式中 View 和 Controller 的关系就有点像 中介者模式 </p>
<p>View想要访问另一个View 就通过Controller调用各种Model ，条件判断 ，最终返回另一个View</p>
</blockquote>
<h4 id="注意事项和细节"><a href="#注意事项和细节" class="headerlink" title="注意事项和细节"></a>注意事项和细节</h4><ol>
<li>多个类相互耦合，会形成网状结构，使用终结者模式将网状结构分离为星形结构，进行了解耦</li>
<li>减少了类间依赖，降低了耦合，符合了迪米特法则</li>
<li> 中介者承担了较多的责任，一旦中介者出现了问题，整个系统就会受到影响</li>
<li>如果设计不当，中介者对象本身变得过于复杂，这点在实际使用的时候要注意，代码要谨慎写。</li>
</ol>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/designMode/">designMode</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客目前大部分文章都是参考尚硅谷或者马士兵教育的学习资料！<a href="http://www.atguigu.com/" rel="nofollow noopener"官网地址！</a> 
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/12/10/springMVC-01/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">springMVC-01</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/12/08/java-builder/">
                        <span class="hidden-mobile">java-构建者模式</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                

              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">

  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
	<!--《添加网站运行时间 -->
<br/>

<span id="timeDate">载入天数...</span><span id="times">载入时分秒...</span>
<script>
var now = new Date(); 

function createtime() {
    //此处修改你的建站时间或者网站上线时间
    var grt = new Date('11/02/2021 21:39:00');
    now.setTime(now.getTime() + 250);
    days = (now - grt) / 1000 / 60 / 60 / 24;

    dnum = Math.floor(days);
    hours = (now - grt) / 1000 / 60 / 60 - (24 * dnum);
    hnum = Math.floor(hours);
    if (String(hnum).length == 1) {
        hnum = "0" + hnum;
    }
    minutes = (now - grt) / 1000 / 60 - (24 * 60 * dnum) - (60 * hnum);
    mnum = Math.floor(minutes);
    if (String(mnum).length == 1) {
        mnum = "0" + mnum;
    }
    seconds = (now - grt) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
    snum = Math.round(seconds);
    if (String(snum).length == 1) {
        snum = "0" + snum;
    }
    document.getElementById("timeDate").innerHTML = " 本站已各种夹缝中安全运行 " + dnum + " 天 ";
    document.getElementById("times").innerHTML = hnum + " 小时 " + mnum + " 分 " + snum + " 秒";
}
setInterval("createtime()", 250);
</script>

<!-- 添加网站运行时间》-->
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
